package gwtappcontainer.server;

import gwtappcontainer.server.apis.content.ContentAPI;
import gwtappcontainer.shared.apis.APIResponse;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.content.ContentProp;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ContentServlet extends HttpServlet {
	private Logger logger = Logger.getLogger(ContentAPI.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setContentType("text/html");		
		
		ContentAPI contentAPI = new ContentAPI();
		
		final String PARAM_TAG = "tag";
		String tag = req.getParameter(PARAM_TAG);
		
		if (null == tag) {
			String errMessage = "Query param [" + PARAM_TAG + "] not found in query string"; 
			logger.warning(errMessage);
			resp.getWriter().println(errMessage);
			return;
		}
		
		APIResponse response = contentAPI.getContent(tag, null);
		
		if (response.statusCode != Status.SUCCESS) {			
			String errMessage = "Unable to retreive content. Reason(s) could be - <br>" +
					"1) Tag [" + tag + "] is invalid <br>" +
					"2) No content exists for tag [" + tag + "] <br>" +
					"3) The content is not published" + 
					"<br><br> Error message from ContentAPI <br> - " +
					response.userFriendlyMessage;
			
			resp.getWriter().println(errMessage);
			return;
		}
						
		String htmlContent;
		
		ContentProp prop = (ContentProp) response.object;
		htmlContent = prop.html;											
		resp.getWriter().println(htmlContent);				
	}
}
